# -*- coding: utf-8 -*-
import time
from PySide2.QtCore import QThread, Signal
from gglobal import logger


class CheckCarConnectThread(QThread):
    """车辆连接状态检测线程类"""
    
    # 信号定义
    connection_status_checked = Signal(bool, str)  # 连接状态检测结果信号 (是否连接, 消息)
    
    def __init__(self, client_car_thread, check_interval=5, parent=None):
        """
        初始化连接检测线程
        :param client_car_thread: 客户端车辆连接线程对象
        :param check_interval: 检测间隔时间（秒），默认5秒
        :param parent: 父对象
        """
        super().__init__(parent)
        self._client_car_thread = client_car_thread
        self._check_interval = check_interval
        self._stop_flag = False
        
    def run(self):
        """线程主函数 - 定期检测连接状态"""
        logger.info(f"连接状态检测线程已启动，检测间隔: {self._check_interval}秒")
        
        while not self._stop_flag:
            try:
                # 检查连接状态
                is_alive, message = self._check_connection_status()
                
                # 发送检测结果信号
                self.connection_status_checked.emit(is_alive, message)
                
                # 如果连接已断开，停止检测
                if not is_alive:
                    logger.warning(f"连接已断开，停止检测线程: {message}")
                    break
                    
                # 等待指定间隔时间，同时检查停止标志
                for _ in range(self._check_interval * 10):  # 分成0.1秒的小间隔
                    if self._stop_flag:
                        break
                    time.sleep(0.1)
                    
            except Exception as e:
                error_msg = f"连接状态检测时发生错误: {str(e)}"
                logger.error(error_msg)
                self.connection_status_checked.emit(False, error_msg)
                break
                
        logger.info("连接状态检测线程已停止")
    
    def _check_connection_status(self):
        """
        检查连接状态（在子线程中运行，避免阻塞UI）
        :return: tuple (是否连接, 状态消息)
        """
        try:
            # 检查客户端线程和ssh_client是否可用
            if not self._client_car_thread:
                return False, "客户端线程不可用"
                
            if not hasattr(self._client_car_thread, 'ssh_client'):
                return False, "ssh_client属性不存在"
                
            if not self._client_car_thread.ssh_client:
                return False, "ssh_client对象为空"
            
            # 使用paramikomodel的is_connection_alive方法检测连接状态
            # 这个调用可能会阻塞，但现在在子线程中运行，不会影响UI
            is_alive = self._client_car_thread.ssh_client.is_connection_alive()
            
            if is_alive:
                logger.debug("连接状态正常")
                return True, "连接正常"
            else:
                logger.warning("检测到连接已断开")
                return False, "连接已断开"
                
        except Exception as e:
            error_msg = f"连接状态检测异常: {str(e)}"
            logger.error(error_msg)
            return False, error_msg
    
    def stop_checking(self):
        """
        停止连接状态检测
        """
        logger.info("请求停止连接状态检测线程")
        self._stop_flag = True
        
    def update_client_thread(self, client_car_thread):
        """
        更新客户端线程对象
        :param client_car_thread: 新的客户端车辆连接线程对象
        """
        self._client_car_thread = client_car_thread
        logger.debug("连接检测线程的客户端线程对象已更新")
        
    def set_check_interval(self, interval):
        """
        设置检测间隔时间
        :param interval: 检测间隔时间（秒）
        """
        if interval > 0:
            self._check_interval = interval
            logger.info(f"连接检测间隔已更新为: {interval}秒")
        else:
            logger.warning("检测间隔时间必须大于0")
    
    def reconnect_to_vehicle(self):
        """
        重新连接到车辆
        :return: tuple (是否成功, 消息)
        """
        try:
            logger.info("开始尝试重新连接车辆")
            
            # 检查客户端线程和ssh_client是否可用
            if not self._client_car_thread:
                return False, "客户端线程不可用"
                
            if not hasattr(self._client_car_thread, 'ssh_client'):
                return False, "ssh_client属性不存在"
                
            if not self._client_car_thread.ssh_client:
                return False, "ssh_client对象为空"
            
            # 调用paramikomodel的reconnect方法进行重连
            result_message = self._client_car_thread.ssh_client.reconnect(
                check_port=True,
                enable_ssh=True,
                enable_sftp=True,
                enable_channel=True,
                expect_symbol="$ "
            )
            
            # 检查重连是否成功
            if "成功" in result_message:
                logger.info(f"车辆重连成功: {result_message}")
                return True, result_message
            else:
                logger.error(f"车辆重连失败: {result_message}")
                return False, result_message
                
        except Exception as e:
            error_msg = f"重连过程中发生异常: {str(e)}"
            logger.error(error_msg)
            return False, error_msg